<template>
  <div class="breakout-game-container">
    <div class="game-header">
      <h1>🎯 打砖块大师</h1>
      <div class="game-stats">
        <div class="stat-card">
          <div class="stat-label">分数</div>
          <div class="stat-value">{{ score.toLocaleString() }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">关卡</div>
          <div class="stat-value">{{ currentLevel }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">生命</div>
          <div class="stat-value">{{ lives }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">最高分</div>
          <div class="stat-value">{{ highScore.toLocaleString() }}</div>
        </div>
      </div>
    </div>

    <div class="game-content">
      <!-- 左侧信息面板 -->
      <div class="left-panel">
        <div class="power-ups-container">
          <h3>🎁 道具效果</h3>
          <div class="active-powerups">
            <div 
              v-for="powerup in activePowerUps"
              :key="powerup.id"
              class="powerup-item"
            >
              <div class="powerup-icon">{{ powerup.icon }}</div>
              <div class="powerup-info">
                <div class="powerup-name">{{ powerup.name }}</div>
                <div class="powerup-timer">{{ Math.ceil(powerup.remaining / 1000) }}s</div>
              </div>
            </div>
          </div>
          <div v-if="activePowerUps.length === 0" class="no-powerups">
            暂无激活道具
          </div>
        </div>

        <div class="level-info">
          <h3>📊 关卡信息</h3>
          <div class="level-progress">
            <div class="progress-label">砖块剩余</div>
            <div class="progress-bar">
              <div 
                class="progress-fill"
                :style="{ width: (remainingBricks / totalBricks) * 100 + '%' }"
              ></div>
            </div>
            <div class="progress-text">{{ remainingBricks }}/{{ totalBricks }}</div>
          </div>
        </div>

        <div class="controls-info">
          <h3>🎮 操作说明</h3>
          <div class="control-item">
            <span class="key">A/D</span>
            <span class="action">移动挡板</span>
          </div>
          <div class="control-item">
            <span class="key">←/→</span>
            <span class="action">移动挡板</span>
          </div>
          <div class="control-item">
            <span class="key">空格</span>
            <span class="action">发射球/暂停</span>
          </div>
          <div class="control-item">
            <span class="key">R</span>
            <span class="action">重新开始</span>
          </div>
        </div>
      </div>

      <!-- 游戏主区域 -->
      <div class="game-main">
        <div class="game-controls">
          <button @click="startGame" :disabled="gameRunning" class="control-btn start">
            {{ gameRunning ? '游戏进行中' : '开始游戏' }}
          </button>
          <button @click="pauseGame" :disabled="!gameRunning" class="control-btn pause">
            {{ gamePaused ? '继续' : '暂停' }}
          </button>
          <button @click="resetGame" class="control-btn reset">重新开始</button>
        </div>

        <div class="game-canvas-wrapper">
          <canvas
            ref="gameCanvas"
            :width="canvasWidth"
            :height="canvasHeight"
            class="game-canvas"
            @mousemove="handleMouseMove"
            @keydown="handleKeyPress"
            tabindex="0"
          ></canvas>

          <!-- 游戏状态覆盖层 -->
          <div v-if="!gameRunning && !gameOver" class="game-overlay start-overlay">
            <div class="overlay-content">
              <h2>🎯 准备开始</h2>
              <p>经典打砖块游戏</p>
              <p>消除所有砖块来过关</p>
              <button @click="startGame" class="overlay-btn">开始游戏</button>
            </div>
          </div>

          <div v-if="gamePaused" class="game-overlay pause-overlay">
            <div class="overlay-content">
              <h2>⏸️ 游戏暂停</h2>
              <p>按空格键或点击继续按钮恢复游戏</p>
              <button @click="pauseGame" class="overlay-btn">继续游戏</button>
            </div>
          </div>

          <div v-if="gameOver" class="game-overlay game-over-overlay">
            <div class="overlay-content">
              <h2>💀 游戏结束</h2>
              <p>最终分数: <strong>{{ score.toLocaleString() }}</strong></p>
              <p>达到关卡: <strong>{{ currentLevel }}</strong></p>
              <p v-if="isNewHighScore" class="new-record">🎉 新纪录！</p>
              <button @click="resetGame" class="overlay-btn">重新开始</button>
            </div>
          </div>

          <div v-if="levelComplete" class="game-overlay level-complete-overlay">
            <div class="overlay-content">
              <h2>🎊 关卡完成！</h2>
              <p>恭喜通过第 {{ currentLevel }} 关</p>
              <p>获得分数: <strong>{{ levelBonus.toLocaleString() }}</strong></p>
              <button @click="nextLevel" class="overlay-btn">下一关</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧信息面板 -->
      <div class="right-panel">
        <div class="combo-display" v-if="combo > 1">
          <div class="combo-text">{{ combo }}x 连击!</div>
          <div class="combo-effect"></div>
        </div>

        <div class="achievements">
          <h3>🏆 成就</h3>
          <div class="achievement-list">
            <div 
              v-for="achievement in achievements"
              :key="achievement.id"
              :class="['achievement', { unlocked: achievement.unlocked }]"
            >
              <div class="achievement-icon">{{ achievement.icon }}</div>
              <div class="achievement-text">
                <div class="achievement-name">{{ achievement.name }}</div>
                <div class="achievement-desc">{{ achievement.description }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="game-tips">
          <h3>💡 游戏提示</h3>
          <div class="tip-list">
            <div class="tip-item">击中砖块边缘可以改变球的角度</div>
            <div class="tip-item">收集道具可以获得特殊能力</div>
            <div class="tip-item">连续击中砖块可以获得连击加分</div>
            <div class="tip-item">不同颜色的砖块有不同的分数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 粒子效果容器 -->
    <div class="particles-container">
      <div
        v-for="particle in particles"
        :key="particle.id"
        class="particle"
        :style="particle.style"
      ></div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'

export default {
  name: 'BreakoutGame',
  setup() {
    // 游戏配置
    const canvasWidth = 800
    const canvasHeight = 600
    const paddleWidth = 100
    const paddleHeight = 15
    const ballRadius = 8
    const brickRows = 8
    const brickCols = 10
    const brickWidth = 75
    const brickHeight = 20
    const brickPadding = 5
    const brickOffsetTop = 60
    const brickOffsetLeft = 35
    
    // 游戏状态
    const gameRunning = ref(false)
    const gamePaused = ref(false)
    const gameOver = ref(false)
    const levelComplete = ref(false)
    const score = ref(0)
    const currentLevel = ref(1)
    const lives = ref(3)
    const highScore = ref(parseInt(localStorage.getItem('breakoutHighScore') || '0'))
    const isNewHighScore = ref(false)
    const combo = ref(0)
    const levelBonus = ref(0)
    
    // 游戏对象
    const paddle = reactive({
      x: canvasWidth / 2 - paddleWidth / 2,
      y: canvasHeight - paddleHeight - 10,
      width: paddleWidth,
      height: paddleHeight,
      speed: 8
    })
    
    const ball = reactive({
      x: canvasWidth / 2,
      y: canvasHeight - 30,
      dx: 4,
      dy: -4,
      radius: ballRadius,
      speed: 4
    })
    
    const bricks = ref([])
    const powerUps = ref([])
    const activePowerUps = ref([])
    const particles = ref([])
    
    // 砖块类型定义
    const brickTypes = [
      { color: '#ff6b6b', points: 10, hits: 1 },  // 红色 - 1击
      { color: '#4ecdc4', points: 20, hits: 1 },  // 青色 - 1击
      { color: '#45b7d1', points: 30, hits: 1 },  // 蓝色 - 1击
      { color: '#96ceb4', points: 40, hits: 1 },  // 绿色 - 1击
      { color: '#feca57', points: 50, hits: 2 },  // 黄色 - 2击
      { color: '#ff9ff3', points: 60, hits: 2 },  // 粉色 - 2击
      { color: '#54a0ff', points: 70, hits: 3 },  // 深蓝 - 3击
      { color: '#5f27cd', points: 100, hits: 3 }  // 紫色 - 3击
    ]
    
    // 道具类型定义
    const powerUpTypes = [
      { 
        type: 'expand', 
        icon: '📏', 
        name: '扩大挡板', 
        color: '#4ecdc4',
        duration: 15000,
        effect: () => { paddle.width = Math.min(paddle.width * 1.5, 200) }
      },
      { 
        type: 'multiball', 
        icon: '⚽', 
        name: '多球', 
        color: '#ff6b6b',
        duration: 0,
        effect: () => { createMultiBall() }
      },
      { 
        type: 'slowball', 
        icon: '🐌', 
        name: '慢速球', 
        color: '#feca57',
        duration: 10000,
        effect: () => { ball.speed = Math.max(ball.speed * 0.7, 2) }
      },
      { 
        type: 'fastball', 
        icon: '⚡', 
        name: '快速球', 
        color: '#ff9ff3',
        duration: 8000,
        effect: () => { ball.speed = Math.min(ball.speed * 1.3, 8) }
      },
      { 
        type: 'penetrate', 
        icon: '💥', 
        name: '穿透球', 
        color: '#5f27cd',
        duration: 12000,
        effect: () => { ball.penetrating = true }
      }
    ]
    
    // 成就系统
    const achievements = ref([
      { id: 1, name: '初学者', description: '完成第一关', icon: '🎯', unlocked: false },
      { id: 2, name: '连击高手', description: '达成10连击', icon: '🔥', unlocked: false },
      { id: 3, name: '速度之王', description: '完成第5关', icon: '⚡', unlocked: false },
      { id: 4, name: '砖块杀手', description: '得分超过5000', icon: '💀', unlocked: false },
      { id: 5, name: '完美主义', description: '一局不失球', icon: '💎', unlocked: false }
    ])
    
    // Canvas 相关
    const gameCanvas = ref(null)
    let ctx = null
    let gameLoop = null
    let balls = []
    
    // 计算属性
    const remainingBricks = ref(0)
    const totalBricks = ref(0)
    
    // 初始化砖块
    const initializeBricks = () => {
      bricks.value = []
      
      for (let r = 0; r < brickRows; r++) {
        for (let c = 0; c < brickCols; c++) {
          const brickTypeIndex = Math.min(r, brickTypes.length - 1)
          const brickType = brickTypes[brickTypeIndex]
          
          bricks.value.push({
            x: c * (brickWidth + brickPadding) + brickOffsetLeft,
            y: r * (brickHeight + brickPadding) + brickOffsetTop,
            width: brickWidth,
            height: brickHeight,
            color: brickType.color,
            points: brickType.points,
            maxHits: brickType.hits,
            hits: 0,
            visible: true
          })
        }
      }
      
      totalBricks.value = bricks.value.length
      remainingBricks.value = bricks.value.filter(brick => brick.visible).length
    }
    
    // 初始化球
    const initializeBall = () => {
      ball.x = paddle.x + paddle.width / 2
      ball.y = paddle.y - ball.radius
      ball.dx = (Math.random() - 0.5) * 6
      ball.dy = -Math.abs(ball.dy)
      ball.speed = 4
      ball.penetrating = false
      balls = [ball]
    }
    
    // 创建多球道具效果
    const createMultiBall = () => {
      for (let i = 0; i < 2; i++) {
        const newBall = {
          x: ball.x,
          y: ball.y,
          dx: (Math.random() - 0.5) * 8,
          dy: -4,
          radius: ballRadius,
          speed: ball.speed,
          penetrating: ball.penetrating
        }
        balls.push(newBall)
      }
    }
    
    // 绘制游戏
    const draw = () => {
      if (!ctx) return
      
      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制背景渐变
      const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight)
      gradient.addColorStop(0, '#1e3c72')
      gradient.addColorStop(1, '#2a5298')
      ctx.fillStyle = gradient
      ctx.fillRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制砖块
      bricks.value.forEach(brick => {
        if (brick.visible) {
          // 砖块主体
          ctx.fillStyle = brick.color
          ctx.fillRect(brick.x, brick.y, brick.width, brick.height)
          
          // 砖块边框
          ctx.strokeStyle = 'rgba(255,255,255,0.3)'
          ctx.lineWidth = 1
          ctx.strokeRect(brick.x, brick.y, brick.width, brick.height)
          
          // 显示耐久度
          if (brick.maxHits > 1) {
            ctx.fillStyle = 'white'
            ctx.font = '12px Arial'
            ctx.textAlign = 'center'
            ctx.fillText(
              brick.maxHits - brick.hits,
              brick.x + brick.width / 2,
              brick.y + brick.height / 2 + 4
            )
          }
        }
      })
      
      // 绘制挡板
      const paddleGradient = ctx.createLinearGradient(paddle.x, paddle.y, paddle.x, paddle.y + paddle.height)
      paddleGradient.addColorStop(0, '#4ecdc4')
      paddleGradient.addColorStop(1, '#44a08d')
      ctx.fillStyle = paddleGradient
      ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height)
      
      // 挡板边框
      ctx.strokeStyle = 'rgba(255,255,255,0.5)'
      ctx.lineWidth = 2
      ctx.strokeRect(paddle.x, paddle.y, paddle.width, paddle.height)
      
      // 绘制所有球
      balls.forEach(ballObj => {
        ctx.beginPath()
        ctx.arc(ballObj.x, ballObj.y, ballObj.radius, 0, Math.PI * 2)
        
        if (ballObj.penetrating) {
          const ballGradient = ctx.createRadialGradient(ballObj.x, ballObj.y, 0, ballObj.x, ballObj.y, ballObj.radius)
          ballGradient.addColorStop(0, '#ff6b6b')
          ballGradient.addColorStop(1, '#ff9ff3')
          ctx.fillStyle = ballGradient
        } else {
          const ballGradient = ctx.createRadialGradient(ballObj.x, ballObj.y, 0, ballObj.x, ballObj.y, ballObj.radius)
          ballGradient.addColorStop(0, '#ffd700')
          ballGradient.addColorStop(1, '#ff8c00')
          ctx.fillStyle = ballGradient
        }
        
        ctx.fill()
        ctx.strokeStyle = 'rgba(255,255,255,0.8)'
        ctx.lineWidth = 1
        ctx.stroke()
        ctx.closePath()
      })
      
      // 绘制道具
      powerUps.value.forEach(powerUp => {
        ctx.fillStyle = powerUp.color
        ctx.fillRect(powerUp.x, powerUp.y, powerUp.width, powerUp.height)
        
        ctx.fillStyle = 'white'
        ctx.font = '16px Arial'
        ctx.textAlign = 'center'
        ctx.fillText(powerUp.icon, powerUp.x + powerUp.width / 2, powerUp.y + powerUp.height / 2 + 6)
      })
    }
    
    // 更新游戏状态
    const update = () => {
      if (!gameRunning.value || gamePaused.value) return
      
      // 更新所有球
      balls.forEach((ballObj, index) => {
        ballObj.x += ballObj.dx
        ballObj.y += ballObj.dy
        
        // 球与墙壁碰撞
        if (ballObj.x + ballObj.radius > canvasWidth || ballObj.x - ballObj.radius < 0) {
          ballObj.dx = -ballObj.dx
        }
        
        if (ballObj.y - ballObj.radius < 0) {
          ballObj.dy = -ballObj.dy
        }
        
        // 球掉落
        if (ballObj.y + ballObj.radius > canvasHeight) {
          balls.splice(index, 1)
          
          if (balls.length === 0) {
            lives.value--
            if (lives.value <= 0) {
              endGame()
            } else {
              initializeBall()
            }
          }
          return
        }
        
        // 球与挡板碰撞
        if (ballObj.y + ballObj.radius > paddle.y &&
            ballObj.x > paddle.x &&
            ballObj.x < paddle.x + paddle.width) {
          
          // 计算碰撞点相对于挡板中心的位置
          const hitPos = (ballObj.x - (paddle.x + paddle.width / 2)) / (paddle.width / 2)
          ballObj.dx = hitPos * 5
          ballObj.dy = -Math.abs(ballObj.dy)
        }
        
        // 球与砖块碰撞
        bricks.value.forEach(brick => {
          if (brick.visible &&
              ballObj.x + ballObj.radius > brick.x &&
              ballObj.x - ballObj.radius < brick.x + brick.width &&
              ballObj.y + ballObj.radius > brick.y &&
              ballObj.y - ballObj.radius < brick.y + brick.height) {
            
            if (!ballObj.penetrating) {
              ballObj.dy = -ballObj.dy
            }
            
            brick.hits++
            
            if (brick.hits >= brick.maxHits) {
              brick.visible = false
              score.value += brick.points * (combo.value + 1)
              combo.value++
              
              // 创建粒子效果
              createBrickParticles(brick.x + brick.width / 2, brick.y + brick.height / 2, brick.color)
              
              // 随机生成道具
              if (Math.random() < 0.15) {
                createPowerUp(brick.x + brick.width / 2, brick.y + brick.height / 2)
              }
              
              remainingBricks.value--
              
              if (remainingBricks.value === 0) {
                completeLevel()
              }
            }
          }
        })
      })
      
      // 更新道具
      powerUps.value.forEach((powerUp, index) => {
        powerUp.y += powerUp.speed
        
        // 道具与挡板碰撞
        if (powerUp.y + powerUp.height > paddle.y &&
            powerUp.x + powerUp.width > paddle.x &&
            powerUp.x < paddle.x + paddle.width) {
          
          activatePowerUp(powerUp.type)
          powerUps.value.splice(index, 1)
        }
        
        // 道具掉落
        if (powerUp.y > canvasHeight) {
          powerUps.value.splice(index, 1)
        }
      })
      
      // 更新激活的道具
      activePowerUps.value.forEach((powerUp, index) => {
        powerUp.remaining -= 16 // 假设60FPS
        
        if (powerUp.remaining <= 0) {
          deactivatePowerUp(powerUp.type)
          activePowerUps.value.splice(index, 1)
        }
      })
      
      // 重置连击计数器
      if (combo.value > 0) {
        setTimeout(() => {
          if (combo.value > 0) combo.value = 0
        }, 2000)
      }
    }
    
    // 创建道具
    const createPowerUp = (x, y) => {
      const powerUpType = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)]
      
      powerUps.value.push({
        x: x - 15,
        y: y,
        width: 30,
        height: 20,
        speed: 2,
        type: powerUpType.type,
        icon: powerUpType.icon,
        color: powerUpType.color
      })
    }
    
    // 激活道具
    const activatePowerUp = (type) => {
      const powerUpType = powerUpTypes.find(p => p.type === type)
      if (!powerUpType) return
      
      powerUpType.effect()
      
      if (powerUpType.duration > 0) {
        activePowerUps.value.push({
          id: Date.now(),
          type: type,
          name: powerUpType.name,
          icon: powerUpType.icon,
          remaining: powerUpType.duration
        })
      }
    }
    
    // 取消道具效果
    const deactivatePowerUp = (type) => {
      switch (type) {
        case 'expand':
          paddle.width = paddleWidth
          break
        case 'slowball':
        case 'fastball':
          ball.speed = 4
          balls.forEach(ballObj => {
            ballObj.speed = 4
          })
          break
        case 'penetrate':
          balls.forEach(ballObj => {
            ballObj.penetrating = false
          })
          break
      }
    }
    
    // 创建砖块粒子效果
    const createBrickParticles = (x, y, color) => {
      for (let i = 0; i < 8; i++) {
        createParticle(x, y, color)
      }
    }
    
    // 创建粒子
    const createParticle = (x, y, color) => {
      const particle = {
        id: Date.now() + Math.random(),
        style: {
          position: 'absolute',
          left: `${x}px`,
          top: `${y}px`,
          width: '4px',
          height: '4px',
          backgroundColor: color,
          borderRadius: '50%',
          pointerEvents: 'none',
          animation: 'particleExplode 0.8s ease-out forwards'
        }
      }
      
      particles.value.push(particle)
      
      setTimeout(() => {
        particles.value = particles.value.filter(p => p.id !== particle.id)
      }, 800)
    }
    
    // 完成关卡
    const completeLevel = () => {
      levelComplete.value = true
      gameRunning.value = false
      
      levelBonus.value = currentLevel.value * 1000
      score.value += levelBonus.value
      
      checkAchievements()
    }
    
    // 下一关
    const nextLevel = () => {
      currentLevel.value++
      levelComplete.value = false
      
      initializeBricks()
      initializeBall()
      
      // 重置道具效果
      activePowerUps.value = []
      powerUps.value = []
      paddle.width = paddleWidth
      
      startGame()
    }
    
    // 检查成就
    const checkAchievements = () => {
      // 初学者：完成第一关
      if (currentLevel.value >= 1 && !achievements.value[0].unlocked) {
        unlockAchievement(0)
      }
      
      // 连击高手：达成10连击
      if (combo.value >= 10 && !achievements.value[1].unlocked) {
        unlockAchievement(1)
      }
      
      // 速度之王：完成第5关
      if (currentLevel.value >= 5 && !achievements.value[2].unlocked) {
        unlockAchievement(2)
      }
      
      // 砖块杀手：得分超过5000
      if (score.value >= 5000 && !achievements.value[3].unlocked) {
        unlockAchievement(3)
      }
    }
    
    // 解锁成就
    const unlockAchievement = (index) => {
      achievements.value[index].unlocked = true
      console.log(`成就解锁: ${achievements.value[index].name}`)
    }
    
    // 游戏控制方法
    const startGame = () => {
      if (gameRunning.value) return
      
      gameRunning.value = true
      gamePaused.value = false
      gameOver.value = false
      levelComplete.value = false
      
      if (!bricks.value.length) {
        initializeBricks()
      }
      
      if (!balls.length) {
        initializeBall()
      }
      
      gameLoop = setInterval(() => {
        update()
        draw()
      }, 16) // 60 FPS
      
      nextTick(() => {
        gameCanvas.value?.focus()
      })
    }
    
    const pauseGame = () => {
      if (!gameRunning.value) return
      
      gamePaused.value = !gamePaused.value
      
      if (gamePaused.value) {
        clearInterval(gameLoop)
      } else {
        gameLoop = setInterval(() => {
          update()
          draw()
        }, 16)
        nextTick(() => {
          gameCanvas.value?.focus()
        })
      }
    }
    
    const resetGame = () => {
      clearInterval(gameLoop)
      
      gameRunning.value = false
      gamePaused.value = false
      gameOver.value = false
      levelComplete.value = false
      score.value = 0
      currentLevel.value = 1
      lives.value = 3
      combo.value = 0
      isNewHighScore.value = false
      
      // 重置游戏对象
      paddle.x = canvasWidth / 2 - paddleWidth / 2
      paddle.width = paddleWidth
      
      balls = []
      powerUps.value = []
      activePowerUps.value = []
      particles.value = []
      
      // 重置成就
      achievements.value.forEach(achievement => {
        achievement.unlocked = false
      })
      
      initializeBricks()
      draw()
    }
    
    const endGame = () => {
      clearInterval(gameLoop)
      
      gameRunning.value = false
      gameOver.value = true
      
      // 检查最高分
      if (score.value > highScore.value) {
        highScore.value = score.value
        isNewHighScore.value = true
        localStorage.setItem('breakoutHighScore', score.value.toString())
      }
    }
    
    // 事件处理
    const handleKeyPress = (event) => {
      if (!gameRunning.value && !gamePaused.value) return
      
      const key = event.key.toLowerCase()
      
      switch (key) {
        case 'a':
        case 'arrowleft':
          if (paddle.x > 0) {
            paddle.x = Math.max(0, paddle.x - paddle.speed)
          }
          break
        case 'd':
        case 'arrowright':
          if (paddle.x < canvasWidth - paddle.width) {
            paddle.x = Math.min(canvasWidth - paddle.width, paddle.x + paddle.speed)
          }
          break
        case ' ':
          pauseGame()
          break
        case 'r':
          resetGame()
          break
      }
      
      event.preventDefault()
    }
    
    const handleMouseMove = (event) => {
      if (!gameRunning.value || gamePaused.value) return
      
      const rect = gameCanvas.value.getBoundingClientRect()
      const mouseX = event.clientX - rect.left
      
      paddle.x = Math.max(0, Math.min(canvasWidth - paddle.width, mouseX - paddle.width / 2))
    }
    
    // 生命周期
    onMounted(() => {
      ctx = gameCanvas.value.getContext('2d')
      initializeBricks()
      draw()
      
      document.addEventListener('keydown', handleKeyPress)
    })
    
    onUnmounted(() => {
      clearInterval(gameLoop)
      document.removeEventListener('keydown', handleKeyPress)
    })
    
    return {
      // 响应式数据
      gameRunning,
      gamePaused,
      gameOver,
      levelComplete,
      score,
      currentLevel,
      lives,
      highScore,
      isNewHighScore,
      combo,
      levelBonus,
      remainingBricks,
      totalBricks,
      activePowerUps,
      particles,
      achievements,
      gameCanvas,
      canvasWidth,
      canvasHeight,
      
      // 方法
      startGame,
      pauseGame,
      resetGame,
      nextLevel,
      handleKeyPress,
      handleMouseMove
    }
  }
}
</script>

<style scoped>
.breakout-game-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  color: white;
}

.game-header {
  text-align: center;
  margin-bottom: 30px;
}

.game-header h1 {
  font-size: 3em;
  margin-bottom: 20px;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4);
  background-size: 400% 400%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: gradientShift 3s ease infinite;
}

@keyframes gradientShift {
  0%, 100% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
}

.game-stats {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-card {
  background: rgba(255,255,255,0.1);
  padding: 15px 20px;
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255,255,255,0.2);
  text-align: center;
  min-width: 100px;
}

.stat-label {
  font-size: 0.9em;
  opacity: 0.8;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 1.5em;
  font-weight: bold;
  color: #ffd700;
}

.game-content {
  display: grid;
  grid-template-columns: 250px 1fr 250px;
  gap: 30px;
  align-items: start;
}

.left-panel, .right-panel {
  background: rgba(255,255,255,0.1);
  padding: 20px;
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255,255,255,0.2);
}

.power-ups-container, .level-info, .controls-info {
  margin-bottom: 30px;
}

.power-ups-container h3, .level-info h3, .controls-info h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #ffd700;
}

.active-powerups {
  max-height: 150px;
  overflow-y: auto;
}

.powerup-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  background: rgba(255,255,255,0.1);
  border-radius: 8px;
}

.powerup-icon {
  font-size: 1.2em;
  margin-right: 10px;
}

.powerup-info {
  flex: 1;
}

.powerup-name {
  font-size: 0.9em;
  font-weight: bold;
}

.powerup-timer {
  font-size: 0.8em;
  opacity: 0.8;
}

.no-powerups {
  text-align: center;
  opacity: 0.6;
  font-style: italic;
}

.level-progress {
  margin-bottom: 15px;
}

.progress-label {
  font-size: 0.9em;
  margin-bottom: 5px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: rgba(255,255,255,0.2);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
  margin-top: 5px;
  font-size: 0.8em;
}

.control-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 0.9em;
}

.control-item .key {
  background: #34495e;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: monospace;
  font-weight: bold;
  min-width: 40px;
  text-align: center;
}

.game-main {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.game-controls {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.control-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255,255,255,0.2);
}

.control-btn.start {
  background: linear-gradient(45deg, #2ecc71, #27ae60);
  color: white;
}

.control-btn.pause {
  background: linear-gradient(45deg, #f39c12, #e67e22);
  color: white;
}

.control-btn.reset {
  background: linear-gradient(45deg, #e74c3c, #c0392b);
  color: white;
}

.control-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}

.control-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.game-canvas-wrapper {
  position: relative;
  border: 3px solid #34495e;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}

.game-canvas {
  display: block;
  background: #2c3e50;
  outline: none;
  cursor: none;
}

.game-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(5px);
}

.overlay-content {
  text-align: center;
  background: rgba(255,255,255,0.1);
  padding: 40px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255,255,255,0.2);
}

.overlay-content h2 {
  font-size: 2.5em;
  margin-bottom: 20px;
  color: #ffd700;
}

.overlay-content p {
  font-size: 1.2em;
  margin-bottom: 15px;
  color: #ecf0f1;
}

.new-record {
  color: #ffd700 !important;
  font-weight: bold;
  font-size: 1.5em !important;
  animation: celebration 1s infinite;
}

@keyframes celebration {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.overlay-btn {
  padding: 15px 30px;
  border: none;
  border-radius: 25px;
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(45deg, #3498db, #2980b9);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 20px;
}

.overlay-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}

.combo-display {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
}

.combo-text {
  font-size: 1.5em;
  font-weight: bold;
  color: #ff6b6b;
  animation: comboGlow 1s infinite;
}

@keyframes comboGlow {
  0%, 100% { text-shadow: 0 0 5px #ff6b6b; }
  50% { text-shadow: 0 0 20px #ff6b6b, 0 0 30px #ff6b6b; }
}

.achievements h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #ffd700;
}

.achievement-list {
  max-height: 200px;
  overflow-y: auto;
}

.achievement {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
  background: rgba(255,255,255,0.05);
  opacity: 0.5;
  transition: all 0.3s ease;
}

.achievement.unlocked {
  opacity: 1;
  background: rgba(255,215,0,0.2);
  border: 1px solid rgba(255,215,0,0.5);
}

.achievement-icon {
  font-size: 1.5em;
  margin-right: 10px;
}

.achievement-text {
  flex: 1;
}

.achievement-name {
  font-weight: bold;
  margin-bottom: 2px;
}

.achievement-desc {
  font-size: 0.8em;
  opacity: 0.8;
}

.game-tips h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #ffd700;
}

.tip-list {
  max-height: 150px;
  overflow-y: auto;
}

.tip-item {
  padding: 8px;
  margin-bottom: 8px;
  background: rgba(255,255,255,0.05);
  border-radius: 6px;
  font-size: 0.9em;
  line-height: 1.4;
}

.particles-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1000;
}

.particle {
  position: absolute;
  border-radius: 50%;
}

@keyframes particleExplode {
  to {
    transform: translate(var(--random-x, 0), var(--random-y, 0)) scale(0);
    opacity: 0;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .game-content {
    grid-template-columns: 200px 1fr 200px;
    gap: 20px;
  }
  
  .left-panel, .right-panel {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .game-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .left-panel, .right-panel {
    order: 2;
  }
  
  .game-main {
    order: 1;
  }
  
  .game-header h1 {
    font-size: 2em;
  }
  
  .game-stats {
    gap: 10px;
  }
  
  .stat-card {
    padding: 10px 15px;
    min-width: 80px;
  }
  
  .game-canvas {
    width: 100%;
    max-width: 400px;
    height: auto;
  }
}
</style>